package com.xmall.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.order.define.dict.RefundStatusEnum;
import com.xmall.order.utils.ConvertUtils;
import com.xmall.order.entity.OrderRefund;
import com.xmall.order.entity.OrderRefundHistory;
import com.xmall.order.mapper.OrderRefundHistoryMapper;
import com.xmall.order.service.IOrderRefundHistoryService;
import com.xmall.order.service.IOrderRefundService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单退款退货历史记录 服务实现类
 */
@Service
public class OrderRefundHistoryServiceImpl extends ServiceImpl<OrderRefundHistoryMapper, OrderRefundHistory> implements IOrderRefundHistoryService {

    @Resource
    private IOrderRefundService orderRefundService;

    /**
     * 已拒绝记录存入历史表
     */
    @Override
    public void moveToHistory(Long orderId, Long orderItemId) {
        QueryWrapper<OrderRefund> wrapper = new QueryWrapper<OrderRefund>()
            .eq("order_id", orderId)
            .in("refund_status", Arrays.asList(RefundStatusEnum.REFUSE.getStatus(), RefundStatusEnum.CANCELED.getStatus()));
        wrapper.isNull(null == orderItemId, "order_item_id");
        wrapper.eq(null != orderItemId, "order_item_id", orderItemId);

        List<OrderRefund> orderRefundList = orderRefundService.list(wrapper);
        if(CollectionUtil.isNotEmpty(orderRefundList)) {
            orderRefundService.removeBatchByIds(orderRefundList);
            this.saveBatch(orderRefundList.stream().map(orderRefund -> ConvertUtils.OrderRefundModule.INSTANCE.toHistory(orderRefund)).collect(Collectors.toList()));
        }
    }

}
